import os
import logging
import re

def writetofile(filename,thestr):
    f = open(filename,"w")
    print>>f,thestr
    f.close()

def dicwritetofile(filename,thedic):
    """
    output the dic to the file
    """
    f = open(filename,"w")
    for k in thedic.keys():
        print>>f,str(k)+":"+str(thedic[k])
    f.close()

def listwritetofile(filename,thelist,beginindex,length):
    f = open(filename,"w")
    for i in range(beginindex,beginindex+length):
        print>>f,str(thelist[i])
    f.close()

def myreadlines(filename):
    f = open(filename,"r")
    lines = f.readlines()
    f.close()
    return lines

def mymkdir(dirname):
    """
    try to make and logger.info if exist
    """
    try:
        os.mkdir(dirname)
    except:
        logging.info(dirname+" already exist")

def getfilelist(fpath):
    """
    @fpath the file path to scan, without the last slash in / format
    """
    flist = os.listdir(fpath)
    result  = []
    for f in flist:
        thepath = fpath+"/"+f
        if os.path.isfile(thepath):
            result.append(f)
    return result



def getTermDic(filename):
    """
    terms are splitted with space or tab 
    have many lines
    """
    lines = myreadlines(filename)
    termdic = {}
    for line in lines:
        line.strip()
        words = re.split("\s+",line)
        for w in words:
            if not termdic.has_key(w):
                termdic[w] = 1
            else:
                termdic[w] += 1
    termdic.pop("")
    return termdic


